from django.core.paginator import Paginator, EmptyPage
from django.shortcuts import render
from django import http
from django.utils import timezone

from apps.contents.models import GoodsCategory
from django.views import View
from apps.goods.utils import get_breadcrumb
from meiduo_mall.utils.response_code import RETCODE
from apps.contents.utils import get_categories
# Create your views here.
from apps.goods.models import SKU, GoodsVisitCount
from apps.goods.utils_goods_specs import get_goods_specs



########统计商品分类访问量#############
class DetailVisitView(View):

    def post(self,request,category_id):
        """
        实现统计分类商品访问逻辑
        :param request:
        :param category_id: 要统计的三级分类
        :return: JSON
        """

        # 获取并校验参数category
        try:
            category = GoodsCategory.objects.get(id=category_id)
        except GoodsCategory.DoesNotExist:
            return http.JsonResponse({"code":RETCODE.PARAMERR,"errmsg":"参数category_id"})

        # 获取当天的日期: 日期的类型(时间对象),时间格式(2020-01-15)
        t = timezone.localtime()
        # 将时间对象t拼接成时间字符串(因为t类型正确但是格式不对)
        today_str = "%d-%02d-%02d" % (t.year,t.month,t.day)
        # 将时间字符串转成时间对象(因为today_str 格式正确但是类型不对)
        # strptime: 时间字符串转时间对象. strftime: 将时间对象转时间字符串
        today_date = timezone.datetime.strptime(today_str,"%Y-%m-%d")

        # 判断当天该分类是否有访问记录: 使用category和当天日期作为条件查询记录
        try:
            visit_data = GoodsVisitCount.objects.get(category=category,date=today_date)
        except GoodsVisitCount.DoesNotExist:
            # 如果没有访问记录, 新建记录
            visit_data = GoodsVisitCount()

        # 计算访问量
        visit_data.category = category
        visit_data.date = today_date
        visit_data.count += 1
        visit_data.save()

        # 响应结果
        return http.JsonResponse({"code":RETCODE.OK,"errmsg":"OK"})



########商品详情页############
class DetailView(View):
    """商品详情页"""

    def get(self,request,sku_id):
        """提供商品详情页"""
        # 查询并校验sku
        try:
            sku = SKU.objects.get(id=sku_id)
        except SKU.DoesNotExist:
            return render(request,"404.html")

        # 查询商品分类
        categories = get_categories()

        # 查询面包屑导航
        bread_crumb = get_breadcrumb(sku.category)

        # 查询商品规格
        specs = get_goods_specs(sku)

        # 构造上下文
        context = {
            "categories":categories, # 商品分类
            "bread_crumb":bread_crumb, # 面包屑导航
            "sku":sku, # 商品名称,副标题,价格,图片,总价
            "spu":sku.spu, # 渲染商品的详情,规格与包装,售后服务
            "specs":specs, # 渲染商品的规格
        }

        return render(request,"detail.html",context)



class HotGoodsView(View):
    """热销排行"""

    def get(self,request,category_id):
        """
        # 查询热销排行数据
        :param request:
        :param category_id: 三级分类ID
        :return:  JSON
        """
        # 查询当前三级分类下未被下架的商品,并按照销量降序排序,取前两个.
        skus = SKU.objects.filter(category_id=category_id,is_launched=True).order_by("-sales")[:2]

        # 模型列表转字典列表
        hot_skus = []
        for sku in skus:
            sku_dict = {
                "id":sku.id,
                "default_image_url":sku.default_image.url,
                "name":sku.name,
                "price":sku.price,
            }
            hot_skus.append(sku_dict)

        return http.JsonResponse({"code":RETCODE.OK,"errmsg":"OK","hot_skus":hot_skus})


class ListView(View):
    """商品列表页"""

    def get(self,request,category_id,page_num):
        """
        查询并渲染商品列表页
        :param category_id: 商品的第三级分类
        :param page_num: 用户要看的页码
        :return: list.html
        """
        # 接收参数
        sort = request.GET.get("sort","default")

        # 校验参数
        # 校验category_id是否存在
        try:
            category = GoodsCategory.objects.get(id=category_id)
        except GoodsCategory.DoesNotExist:
            return render(request,"404.html")

        # 查询商品列表数据: 商品分类,面包屑导航,热销排行
        # 查询商品列表数据(排序和分页)
        # 先排序查询: 查询当前指定分类下未被下架的商品,并排序.
        if sort == 'price':  # 按照价格由低到高排序（升序）
            sort_field = 'price'
        elif sort == 'hot':  # 按照销量由高到低排序（降序）
            sort_field = '-sales'
        else:  # 按照创建时间由低到高排序（升序）
            sort = 'default'  # 这个代码就是为了保证无论用户传入什么样的数据，只要是默认的排序，sort必定为default
            sort_field = 'create_time'
            # order_by('必须是模型类的属性')
        skus = SKU.objects.filter(category=category, is_launched=True).order_by(sort_field)

        # 在分页查询
        # 创建分页器
        # paginator = Paginator('要分页的模型列表数据', '每页记录的个数')
        paginator = Paginator(skus, 5)
        # 查询出指定页码中的商品数据
        # page_skus == [<SKU>,<SKU>,<SKU>,<SKU>,<SKU>],共5个.
        try:
            page_skus = paginator.page(page_num)  # paginator.page('页码')
        except EmptyPage:
            return render(request, '404.html')

        # 查询分页后的总页数
        total_page = paginator.num_pages

        # 查询面包屑导航
        bread_crumb = get_breadcrumb(category)


        #  构造上下文
        context = {
            "page_skus":page_skus,
            "category":category,
            "sort":sort,
            "page_num":page_num,
            "total_page":total_page,
            "bread_crumb":bread_crumb,
        }


        return render(request,"list.html",context)

